package com.kuzlak.cms.module.sys.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.kuzlak.cms.module.sys.entity.SysAddress;
import com.kuzlak.cms.module.sys.mapper.SysAddressMapper;
import com.kuzlak.cms.module.sys.service.SysAddressService;
import org.springframework.cache.annotation.Cacheable;
import org.springframework.stereotype.Service;

import java.util.*;

/**
* @author hesenjan
* @description 针对表【sys_address(地区信息表)】的数据库操作Service实现
* @createDate 2024-11-30 23:46:04
*/
@Service
public class SysAddressServiceImpl extends ServiceImpl<SysAddressMapper, SysAddress>
    implements SysAddressService{
    @Cacheable(value = "address", cacheNames = "address", key = "'findByTreeList'+#id+'::level'+#level")
    @Override
    public List<Map<String, Object>> findByTreeList(long id, int level) {


        return findByIdList(id, level,0);
    }

    @Cacheable(value = "address", cacheNames = "address", key = "'findByTreeList::'+#id")
    @Override
    public List<SysAddress> finbyIdList(long id) {
        QueryWrapper<SysAddress> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysAddress::getParentId, id);
        return this.list(queryWrapper);

    }

    @Override
    public boolean deleteById(long id) {
        return this.removeById(id);
    }

    private List<Map<String, Object>> findByIdList(long parentId,int level,int index) {
        index++;
        List<Map<String, Object>> datalist = new ArrayList<>();
        QueryWrapper<SysAddress> queryWrapper = new QueryWrapper<>();
        queryWrapper.lambda().eq(SysAddress::getParentId, parentId);
        List<SysAddress> list = this.list(queryWrapper);
        Iterator<SysAddress> iterator = list.iterator();
        while (iterator.hasNext()) {
            Map<String, Object> map = new HashMap<>();
            SysAddress next = iterator.next();
            map.put("key", next.getId());
            map.put("title", next.getTitle());
            map.put("title2", next.getTitle2());
            // map.put("parentId", next.getParentId());
            String s = String.valueOf(next.getId());
            if (index<level) {
                List<Map<String, Object>> byIdList = findByIdList(next.getId(),level,index);
                if (!byIdList.isEmpty()) {
                    map.put("children", byIdList);
                } else {
                    map.put("children", byIdList);
                }
            } else {
                map.put("children", new ArrayList<Map<String, Object>>());
            }
            datalist.add(map);
        }
        return datalist;
    }
}




